//
//  ReFunnySViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ReFunnySViewController.h"
#import "HotTableViewCell.h"
#import "FLSFirstHotListModel.h"
#import "RecommondSeDetialViewController.h"

@interface ReFunnySViewController ()<UITableViewDataSource, UITableViewDelegate>

// 主页tableView
@property (nonatomic, strong) UITableView *recomTableView;
// 接受季节网址
@property (nonatomic, strong) NSString *seasonURL;
// 接收季节推荐列表
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIImageView *imagV;

@property (nonatomic, strong) AppDelegate *app;

@end

@implementation ReFunnySViewController

- (void)dealloc
{
    // 销毁这条通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NOTIFICATIONONEFUNSEASON" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
     [self freshHeader];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    [self.navigationController.navigationBar setTranslucent:NO];
    // self.view.backgroundColor = [UIColor orangeColor];
    // Do any additional setup after loading the view.
    [self addSubViews];
   
   // [self setUpData];
// #warning 注册一条通知, 注意销毁Notification
    // 注册一条通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(funSeasonNOT:) name:@"NOTIFICATIONONEFUNSEASON" object:nil];
    [self addInternetObserver];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}



- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
    self.recomTableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
    [self.recomTableView.header beginRefreshing];
    } else {
        [self alertController];
    }
}

// 解析数据
- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
    if (_imagV) {
        [_imagV removeFromSuperview];
    }
    // 首次加载 默认是北京
    if (self.seasonURL == nil) {
        self.seasonURL = @"http://app.xialv.com/index2.php?a=sList2&page=1&city_id=1001&type=1";
    }
    // 利用网址字符串创建一个网址对象
    NSURL *url = [NSURL URLWithString:self.seasonURL];
    
    // 利用网址对象创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    
    // 设置请求类型
    [request setHTTPMethod:@"GET"];
// #warning 异步请求利用block方法实现
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    __block ReFunnySViewController  *mySelf = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            return ;
        }
        NSMutableDictionary *datDic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *allArray = datDic[@"result"];
        if (allArray.count == 0) {
           
            _imagV = [[UIImageView alloc] initWithFrame:mySelf.view.bounds];
                _imagV.image = [UIImage imageNamed:@"meiyou_background.jpg"];
                [mySelf.view addSubview:_imagV];
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight / 2 - 100, kScreenWidth, 30)];
                label.text = @"❌ 抱歉! 暂无相关数据!";
                label.textColor = [UIColor redColor];
                label.textAlignment = YES;
                [_imagV addSubview:label];
                [mySelf.view bringSubviewToFront:_imagV];
        }
        mySelf.dataArray = [NSMutableArray array];
        for (NSDictionary *dic in allArray) {
            FLSFirstHotListModel *model = [[FLSFirstHotListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [mySelf.dataArray addObject:model];
        }
        [self.recomTableView.header endRefreshing];
        [mySelf.recomTableView reloadData];
    }];
    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"🙅 您的当前网络中断或网络信号差, 请检查网络后重新进入!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

// NSNotificationCenter实现接收通知的方法
- (void)funSeasonNOT:(NSNotification *)notification
{
    if ([notification.name isEqualToString:@"NOTIFICATIONONEFUNSEASON"]) {
        // 接收通知的参数
        NSDictionary *dic = notification.userInfo;
        
        self.seasonURL = dic[@"funSeason"];
        [self setUpData];
    }
}



// 添加视图
- (void)addSubViews
{
    // tableView
    self.recomTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 104) style:(UITableViewStylePlain)];
    self.recomTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 代理
    self.recomTableView.dataSource = self;
    self.recomTableView.delegate = self;
    [self.view addSubview:self.recomTableView];
}

#pragma mark -- UITableViewDataSource协议
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

// cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"recommCell";
    HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HotTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.dataArray.count > 0) {
        FLSFirstHotListModel *model = self.dataArray[indexPath.row];
        [cell.coverPhoto sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.titleLB.text = model.title;
        
    }
    return cell;
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 215;
}

// 跳转界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RecommondSeDetialViewController *detailVC = [[RecommondSeDetialViewController alloc] init];
    FLSFirstHotListModel *model = self.dataArray[indexPath.row];
    detailVC.headModel = model;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
